#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import sys as osSys
import getopt as osGetopt
from os import popen as osPopen  # 管道处理
import subprocess
import re as osRe
from app import App

class Application(App):
    # 初始配置
    def __init__(self):
        super().__init__()



    def runCommand(self, command, isShowError=False):
        """
        封装通用的 subprocess.Popen 方法。
        
        参数:
        command (str): 要执行的命令
        
        返回:
        output (str): 命令的标准输出结果字符串
        error (str): 命令的标准错误结果字符串
        returncode (int): 进程退出状态码
        """
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,  # 允许使用 shell 命令语句
            universal_newlines=True  # 以字符串格式返回输出结果
        )
        output, error = process.communicate()
        if (isShowError and error.strip()):
            self.myEcho(error.strip(), False)
        
        return output.strip(), error.strip(), process.returncode
    

    # 判断是否亮屏
    def isScreenOn(self):
        command = self.sAdb + ' shell dumpsys window policy|grep isStatusBarKeyguard|cut -d= -f2'
        result = self.runCommand(command)
        return result[2] == "true"


    # 设屏幕亮度
    def setBrightness(self):
        if (not self.isScreenOn()):
            self.setScreenOn()
        print("--- 设置屏幕亮度 ---")
        sShell = self.sAdb + ' shell settings put system screen_brightness ' + str(self.iBrightness)
        # print(sShell)
        self.runCommand(sShell, True)


    # 点亮屏幕
    def setScreenOn(self):
        print("--- 点亮屏幕 ---")
        sShell = self.sAdb +' shell input keyevent 26'
        # print(sShell)
        self.runCommand(sShell, True)
        
    
    # 熄屏feat
    def setScreenOff(self):
        print("--- 熄屏 ---")
        # 该命令会向设备发送两个按键事件，第一个是电源按钮按下（相当于按下熄屏键），第二个是菜单按钮按下（相当于撤销锁屏）。这将使得设备的屏幕关闭，但是设备上的操作不会受到任何影响。 
        sShell = self.sAdb +' shell input keyevent 26 &&'+ self.sAdb +'shell input keyevent 82'
        self.runCommand(sShell, True)


    def startAtx(self):
        print("--- 启动ATX ---")
        sShell = self.sAdb + ' shell /data/local/tmp/atx-agent server -d'
        # print(sShell)
        self.runCommand(sShell, True)


    def startTcpip(self):
        print("--- 启动TCPIP:5555 ---")
        sShell = self.sAdb + ' shell tcpip 5555'
        print(sShell)
        osPopen(sShell)


    def run(self):
        print("--- 开始运行 ---")        
        if (self.sAction == 'at'):
            if (not self.isScreenOn()):
                self.setScreenOn()
            self.startAtx()
            self.startTcpip()
        elif (self.sAction == 'b'):
            self.setBrightness()
        elif (self.sAction == 'on'):
            self.setScreenOn()
        elif (self.sAction == 'off'):
            self.setScreenOff()
        else:
            self.isScreenOn()

        
if __name__ == "__main__":
    app = Application()
    app.run()
    print("DONE")
